<?php 	
/**
 * 团购模块
 */
class tuan {
	public function getView($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $teamId=$param->teamId;
	    Session::switchCustomer(0);
	    $OrderTeamModel = M("module_team_order");
	    $OrderModel = M("module_product_order");
		$productModel = M("module_product");
		$shareModel = M("mishare");
	    $DetailModel = M("module_team_order_detail");
	    $specModel = M("module_product_specification"); 
	    Session::switchCustomer($customerId);
		$distribution = M("module_distribution_scheme");
		$mallInfoModel = M("module_mall_store");
		$userModel = M("user");
		 $weixinUserModel=M("user_weixin_info");
	    $user=$weixinUserModel->where("openid='$userName'")->find();
		$selfBuy = $DetailModel->alias("a")
			->join("inner join wx_module_product_order c on a.oid = c.id")
			->join("left join wx_".$customerId."_user_weixin_info b on a.fromUserName=b.openid")
			->where("a.fromUserName='".$userName."' and a.teamId = $teamId and (c.status = 'teaming' or c.status='ok')")
			->find();
	    $result=$OrderTeamModel->alias("a")
	    ->join("inner join wx_module_product b on a.pid=b.id")
	    ->join("wx_".$customerId."_user_weixin_info user on user.openid=a.fromUserName")
		->join("wx_".$customerId."_user c on c.userName = user.openid")
	    ->field("a.status,a.fromUserName,a.id as teamId,b.id,b.name,b.title,b.picUrl,b.teamStartTime,b.teamEndTime,b.fixedPrice,b.discountedPrice,b.squarePicUrl
	    	,b.teamPrice,b.recommend,b.teamCount,b.recommend,b.priceTag,b.picUrl1,b.vId,b.fromCustomerId,b.picUrl,b.webPageContent,b.distributionId,b.proSource,
	    	user.nickname,user.headimgurl,b.supportSpecification,c.id as uid,b.inventory,b.inventoryCount,b.isChainPro,b.supplyProId,b.json")
	    ->where("a.id=$teamId")
	    ->find();
		if($result['json']){
			$json = json_decode($result["json"],true);
			$jsonName = array_keys($json);
			foreach($jsonName as $key=>$value){
				$result[$value]=$json[$value];
			}
		}
		if($result['isChainPro']){
			$proInfo = $productModel->where("id=".$result['supplyProId'])->find();
			$result['inventory'] = $proInfo['inventory'];
			$result['inventoryCount'] = $proInfo['inventoryCount'];
		}
		if(!$result['distributionId']){
			$distriWhere['isDefault'] = array('eq',1);
			$distriWhere['deleted'] = array('eq',0);
			$distributionInfo = $distribution->where($distriWhere)->field('id')->find();
			$result['distributionId'] = $distributionInfo['id'];
		}
		if($result['picUrl1']){
			$result['picUrl1']=json_decode($result['picUrl1'],true);
		}
		$userInfo = $userModel->where("userName='".$userName."'")->find();
		$mallInfo = $mallInfoModel->find();
		$result["subscribe"]=0;
		if(!$mallInfo['wechaturl']||$userInfo["status"]=='subscribe'||$userInfo["status"]=='scansubscribe'||!isMicroMessengerUserAgent()){
			$result["subscribe"]=1;
		}
		if($result["priceTag"]){
			$result["priceTag"] = explode(",",$result["priceTag"]);
		}
	    if($result["fromUserName"]==$userName) {
	    	$result["isMe"]="1";
	    }
	    $pros=array($result);
	    foreach ($pros as $key=>$val){  
	        // 获取规格
			$pid=$val['id'];
	        if ($val["supportSpecification"] == 1) {
	            $arrFirstSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	            ->order("sepc.id")
	            ->getField("specificationName", true);

	        	$arrFirstSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
				->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
				->order("sepc.id")
				->getField("specificationUrl", true);

	            if ($arrFirstSpec) {
	                $val["sizeUnit"] = $specModel->alias("sepc")->where("sepc.pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.firstSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");
	        
	            }
	            if($arrFirstSpec){
					$val["size"] = json_encode($arrFirstSpec);
	            }
				if ($arrFirstSpecurl) {
					$val["sizeurl"] = json_encode($arrFirstSpecurl);
				}
	            $arrSecSpec = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
	            ->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	            ->getField("specificationName", true);

	        	$arrSecSpecurl = $specModel->alias("sepc")->where("pid=$pid")->distinct("specificationName")
				->join("INNER JOIN wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
				->getField("specificationUrl", true);

	            if ($arrSecSpec) {
	                $val["colorUnit"] = $specModel->alias("sepc")->where("sepc.pid=$pid")->distinct("specificationName")
	                ->join("INNER JOIN  wx_module_product_specification_name specName ON sepc.secSpecificId = specName.id")
	                ->join("INNER JOIN  wx_module_product_specification_group specGroup ON specGroup.id = specName.groupId")
	                ->getField("groupName");
	            }
	            if ($arrSecSpecurl) {
					$val["colorurl"] = json_encode($arrSecSpecurl);
				}
	            if($arrSecSpec) {
	            	$val["color"] = json_encode($arrSecSpec);
	            }
	            if ($val["inventory"] == 1) {
	            	if (isset($arr['availSku'])) {
	                    $availSku=$arr['availSku'];
	                }else{
	                    $params["pid"] = $val['id'];
	                    $params["arrFirstSpec"] = $arrFirstSpec;
	                    $params["arrSecSpec"] = $arrSecSpec;
	                    $availSku = Module::callModule('product', NULL, 'getProductInventory', $params);
	                }
	                $val["availSku"] = json_encode($availSku);
	            }
				if (!isset($val["availSku"])) {
					$val["availSku"] = json_encode(null);
				}
	        }
	        $mipro[$key]=$val;	
	        $newmipro[$pid]=$val;	  
	    }
	    $result['prodetail']=json_encode($newmipro);
	    if($result["teamEndTime"]){
	    	$result["endTime"]=strtotime($result["teamEndTime"])-strtotime(date("Y-m-d H:i:s"));
	    }
		$shareCondition["module"] = array("eq","product");
		$shareCondition["moduleId"] = array("eq",$result["id"]);
		$shareInfo = $shareModel->where($shareCondition)->find();
		$sId = $shareInfo["id"];
		$userOrder = $DetailModel->alias("a")
			->join("inner join wx_module_product_order b on a.oid = b.id")
			->field("b.*")
			->where("a.teamId = $teamId and a.role = 1")->find();
	    $historyBuy=$OrderModel->where("teamId=$teamId and fromUserName='$userName' and wxTransactionId<>''")->find();
		$result["oid"]=$historyBuy["id"];
	    if($userOrder&&$userOrder["qId"]) {
			$Guid = new Guid();
			$guid = $Guid->toString();
			$visitParam=new StdClass();
			$visitParam->guid=$guid;
			$visitParam->sId=$sId;
			$visitParam->fromGuid=$param->fromGuid;
			$visitParam->miUId=$userOrder["miUid"];
			$visitParam->qId=$userOrder["qId"];
			$visitParam->fromPage="product_detail";
			$visitId = Module::callModule("quan", Session::$user,"addVisit", $visitParam);
			$result["visitId"]=$visitId;
			$result["qId"]=$userOrder["qId"];
			$result["miUid"]=$userOrder["miUid"];
			$result["fromGuid"]=$param->fromGuid;
			$result["guid"]=$guid;
			$result["sId"]=$sId;
	    }
	    $price=$result["fixedPrice"];
	    if($result["discountedPrice"]){
	    	$price=$result["discountedPrice"];
	    }
	    $tuanPrice=$result["teamPrice"];
	    $result["multPrice"]=round($price-$tuanPrice,2);
	    if($selfBuy) {
	    	$result["shareHeadImgUrl"]=$user["headimgurl"];
			$result["fromUserName"] = $userName;
	    }else{
			$result["shareHeadImgUrl"]=$result["headimgurl"];
		}
	    
	    $tuanDetailList=$DetailModel->alias("a")
	    ->join("wx_".$customerId."_user_weixin_info user on user.openid=a.fromUserName")
	    ->join("inner join wx_module_product_order b on a.oid=b.id")
	    ->field("a.*,user.headimgurl,user.nickname")
	    ->where("a.teamId=$teamId and (b.wxTransactionId <> '' or b.payType='delivery')")
	    ->select();

	    $result["detailList"]=$tuanDetailList;
	    $result["teamJoinCount"]=count($tuanDetailList);
	    $result["teamId"]=$teamId;
		$result["mall"] = $mallInfo;
		$result["platCustomerId"] = C('PLANT_CUSTOMERID');
		$result['mallHue']=Module::callModule("product",null,"getMallHue",null);
	    Output::instance()->module('tuan',"view")->object($result);
	}
	public function createTeamOrder($param) {
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
	    $teamId=$param->teamId;
	    $pid=$param->pid;
	    $oid=$param->oid;
	    Session::switchCustomer(0);
		$productModel = M("module_product");
	    $OrderModel = M("module_team_order");
		$DetailModel = M("module_team_order_detail");
		Session::switchCustomer($customerId);
		$time=date("Y-m-d H:i:s");
		$OrderModel->startTrans();
		$isTeamOrder=2;
		$proInfo = $productModel->where("id=$pid")->field("teamBack,teamBackMoney,teamCount")->find();
		if(!$teamId) { //开团
			$isTeamOrder=1;
			$orderData=array(
				"fromUserName"=>$userName,
				"pid"=>$pid,
				"deleted"=>0,
				"status"=>0,
				"createTime"=>$time,
				"updateTime"=>$time,
				"openBack"=>$proInfo['teamBack'],
				"backMoney"=>$proInfo['teamBackMoney'],
				"teamCount"=>$proInfo['teamCount']
			);
			$teamId=$OrderModel->add($orderData);
			if($teamId===false) {
				$OrderModel->rollback();
				Output::instance()->resultCode(code_sql_error);
				return;
			}
		}
	    
	    $orderDetailData=array(
			"oid"=>$oid,
			"teamId"=>$teamId,
			"createTime"=>$time,
			"fromUserName"=>$userName,
			"updateTime"=>$time,
			"role"=>$isTeamOrder,
			"count"=>0
		);
		$teamDetailId=$DetailModel->add($orderDetailData);
		if($teamDetailId===false) {
			$OrderModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		$updateStatus=$DetailModel->query("update wx_module_product_order set isTeam=1,teamId=$teamId where id=$oid");
		if($updateStatus===false) {
			$OrderModel->rollback();
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		$OrderModel->commit();
		$out=new stdClass();
		$out->code=0;
		$out->teamId=$teamId;
		Output::instance()->object($out);
		
	}
	//组团中和已经成团的订单列表
	public function getTeamOrderList($param){
		$retVal = Session::init();
	    if (!$retVal) {
	        Output::instance()->resultCode(code_access_denied);
	        return;
	    }
		$pid = $param->pid;
		$phone = $param->unPhone;
		if (empty($pid)) {
			Output::instance()->resultCode(code_lackof_param);
			return;
		}
	    $userName=Session::$user['userName'];
	    $customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$teamOrder = M("module_team_order");
		$teamOrderDetail = M("module_team_order_detail");
		Session::switchCustomer($customerId);
		$arr = $teamOrder->alias("a")
			->field("a.id as teamid,a.pid,d.oid,a.status,b.nickname,b.headimgurl,c.teamPrice,c.teamCount,e.qId,e.miUid")
			->join("inner join wx_".$customerId."_user_weixin_info b on a.fromUserName = b.openid")
			->join("inner join wx_module_product c on a.pid = c.id")
			->join("wx_module_team_order_detail d on a.id = d.teamId")
			->join("wx_module_product_order e on d.oid = e.id")
			->where("c.id = ".$pid." and e.wxTransactionId <> '' and a.status = '0' and e.status <> 'refunding' and e.status <> 'refund'")
			->group("a.id")->order("a.status")
			->select();
		foreach($arr as $key=>$value){
			$teamId = $value['teamid'];
			$count=$teamOrderDetail->alias("a")
				->join("inner join wx_module_product_order b on a.oid = b.id")
				->where("a.teamid=".$teamId." and b.wxTransactionId <> ''")->count();
			$arr[$key]['readyCount']=$count;
			if($value["teamCount"]-$count!=1){
				unset($arr[$key]);
			}
		}
		$result['teamList']=$arr;
		if(!$phone){
			Output::instance()->module('tuan', 'product_teamlist')->object($result);
		}else{
			return count($arr);
		}
	}
}